package test;

import com.itCar.base.tools.DateUtil;
import com.itCar.base.tools.StringUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.springframework.security.web.util.matcher.NegatedRequestMatcher;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.*;

/**
 * @ClassName EntityJson
 * @Description TODO 补充说明:
 * @Author liuzhiguo
 * @Date 2024/1/2 10:41
 * @Version 1.0
 */
public class EntityJson {

    // MySQL数据库连接信息
    private static final String URL = "jdbc:mysql://39.104.67.224:3306/fuel_smart_test?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&allowMultiQueries=true";
    private static final String USER_NAME = "root";
    private static final String PASSWORD = "hhxxhhxx";

    public static void getEntityJSon_copy(String name) {
        try (
                Connection conn = DriverManager.getConnection(URL, USER_NAME, PASSWORD)) {
            DatabaseMetaData metaData = conn.getMetaData();
            ResultSet tablesResultSet = metaData.getTables(null, null, "%", new String[]{"TABLE"});
            // 表结构返回
            JSONArray tableList = new JSONArray();
            // 循环数据库中所有的表
            while (tablesResultSet.next()) {
                // 拿到每一次的表名称
                String tableName = tablesResultSet.getString("TABLE_NAME");
                ResultSet columnsResultSet = null;
                columnsResultSet = metaData.getColumns(null, null, tableName, "%");
                // 存储表结构信息
                JSONObject tableInfo = new JSONObject();
                // 存储表名称
                tableInfo.put("tableName", tableName);
                // 存储表列信息
                JSONArray columnList = new JSONArray();
                while (columnsResultSet.next()) {
                    // 列名
                    String columnName = convertToCamelCase(columnsResultSet.getString("COLUMN_NAME"));
                    JSONObject columnInfo = new JSONObject();
                    columnInfo.put("columnName", columnName);
                    columnList.add(columnInfo);
                }
                tableInfo.put("columns", columnList);
                tableList.add(tableInfo);
            }
            System.out.println(tableList.toJSONString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void getEntityJSon(String name) {
        try (
                Connection conn = DriverManager.getConnection(URL, USER_NAME, PASSWORD)) {
            DatabaseMetaData metaData = conn.getMetaData();
            ResultSet tablesResultSet = metaData.getTables(null, null, "%", new String[]{"TABLE"});
            // 表结构返回
            JSONArray tableList = new JSONArray();
            Map<String, Object> map = null;
            boolean flag = false;
            // 循环数据库中所有的表
            while (tablesResultSet.next()) {
                if (flag){
                    break;
                }
                // 拿到每一次的表名称
                String tableName = tablesResultSet.getString("TABLE_NAME");
                ResultSet columnsResultSet = null;
                // 若指定某张表 只返回指定 否则返回全部
                if (StringUtils.isNotEmpty(name)) {
                    if (name.equals(tableName)) {
                        columnsResultSet = metaData.getColumns(null, null, name, "%");
                        flag = true;
                    } else {
                        continue;
                    }
                } else {
                    columnsResultSet = metaData.getColumns(null, null, tableName, "%");
                }
                // 存储表结构信息
                JSONObject tableInfo = new JSONObject();
                // 存储表名称
                tableInfo.put("tableName", tableName);
                // 存储表列结构信息 例如：{"id":"主键"}
                StringBuilder sb = new StringBuilder("{");
                map = new HashMap<>();
                while (columnsResultSet.next()) {
                    // 列名
                    String columnName = convertToCamelCase(columnsResultSet.getString("COLUMN_NAME"));
                    // 列名注释
                    String columnRemark = columnsResultSet.getString("REMARKS");
                    // 拼接JSON格式 例如：{"id":"主键"}
                    sb.append("\"").append(columnName).append("\"").append(":");
                    sb.append("\"").append(columnRemark).append("\"");
                    if (!columnsResultSet.isLast()) {
                        sb.append(",");
                    }
                    map.put('"'+columnName+'"','"'+columnRemark+'"');
                }
                sb.append("}");
                tableInfo.put("tableFormat", sb);
                tableList.add(tableInfo);
            }

            System.out.println(tableList.toJSONString());
            System.out.println(map.toString().replaceAll("=",":"));
            System.out.println("共" + tableList.size() + "张表");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String convertToCamelCase(String name) {
        StringBuilder result = new StringBuilder();
        // 快速检查
        if (name == null || name.isEmpty()) {
            // 没必要转换
            return "";
        } else if (!name.contains("_")) {
            // 不含下划线，仅将首字母大写
            return name.toLowerCase();
        }
        // 用下划线将原始字符串分割
        String[] camels = name.split("_");
        for (String camel : camels) {
            // 跳过原始字符串中开头、结尾的下换线或双重下划线
            if (camel.isEmpty()) {
                continue;
            }
            // 首字母大写
            result.append(camel.substring(0, 1).toUpperCase());
            result.append(camel.substring(1).toLowerCase());
        }
        StringBuilder ret = new StringBuilder(result.substring(0, 1).toLowerCase());
        ret.append(result.substring(1, result.toString().length()));
        return ret.toString();
    }

    public static void main(String[] args) {
        System.out.println("========开始生成apiPost参数描述库所需数据结构========");
        long start = System.currentTimeMillis();
//        EntityJson.getEntityJSon(null);
        List<String> list = Arrays.asList("t_filling_detail", "t_card_info"); for (String tableName : list) { EntityJson.getEntityJSon(tableName); }
//        System.out.println(convertToCamelCase("t_filling_detail"));
        System.out.println("========结束，用时 " + DateUtil.getDatePoorSec(new Date(System.currentTimeMillis()), new Date(start)) + "========");
    }
}
